package com.vgooo.client.mobile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.analytics.MobclickAgent;
import com.vgooo.bean.Brand;
import com.vgooo.client.R;
import com.vgooo.client.VGActivity;
import com.vgooo.client.ui.HorizontalListView;
import com.vgooo.client.ui.SortAdapter;
import com.vgooo.util.BitmapUtils.PictureLoadingThreadPool;
import com.vgooo.util.DebugTools;
import com.vgooo.util.GSonTools;
import com.vgooo.util.HttpUtils;
import com.vgooo.util.SimpleLoading;
import com.vgooo.util.SimpleLoading.Progress;

public class MobileAlbumDetail_v1 extends VGActivity {

	private static String className = "MobileAlbumDetail";

	private HorizontalListView sort;// 分类列表
	private SortAdapter sortAdapter;
	private int currentSort;
	
	private View hasMore ;

	private ViewPager pager;
	private ViewAdapter adapter;

	private TextView currentIndexTV;// 正在显示的图片索引

	private TextView allCountsTV;// 总图片数

	private int currentIndex;

	private int allCounts;

	private Map<String, List<String>> albums;// 图片信息

	private List<Brand> sorts;// 图片分类信息

	private List<String> urls;// 图片分类信息地址

	private boolean isLoadingIamge = false;// 是否正在加载图片

	private String image_id =""; // 点击图片的名称
	
	private View loading ;
	
	private static Progress mProgress ;
	
	private PictureLoadingThreadPool  albumLoadPool ;

//	// 图片切换动画
//	private Animation left_in;
//	private Animation left_out;
//	private Animation right_in;
//	private Animation right_out;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		detailVeiw = inflater.inflate(R.layout.mobile_album, null);
		setContentView(detailVeiw);
		detailVeiw.setVisibility(View.GONE);
		
		initView();
		addListener();
//		prepareAnim();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// 友盟统计功能，打开页面
		MobclickAgent.onResume(this);
		pager.setVisibility(View.GONE);
		loading.setVisibility(View.INVISIBLE);
		String image_id = getIntent().getStringExtra("image_id");
		if(null==image_id||image_id.equals(this.image_id)){
			detailVeiw.setVisibility(View.VISIBLE);
			pager.setVisibility(View.VISIBLE);
			return ;
		}else{
			this.image_id = image_id;
		}
		init() ;
		isLoadingIamge = false;
		if(mProgress==null){
			mProgress = SimpleLoading.startProgress(loading);
		}else{
			mProgress.start();
		}
		
//		progress =Loading.startProgress(cparent,  loading);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		// 友盟统计功能，页面关闭
		MobclickAgent.onPause(this);
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		mProgress.cancel();
		albumLoadPool.exit();
		super.onDestroy();
	}
	@Override
	public void initView() {
		// TODO Auto-generated method stub
		sort = (HorizontalListView) findViewById(R.id.mobile_album_sort);
		
		hasMore = findViewById(R.id.mobile_album_brands_sort_more) ;

		// 初始化pager
		pager = (ViewPager) findViewById(R.id.mobile_album_view);

		currentIndexTV = (TextView) findViewById(R.id.mobile_album_current_index);

		allCountsTV = (TextView) findViewById(R.id.mobile_album_all_counts);
		
		loading =  findViewById(R.id.mobile_album_loading_image);
	}

//	private void prepareAnim() {
//		left_in = AnimationUtils.loadAnimation(this, R.anim.left_in_slow);
//		left_out = AnimationUtils.loadAnimation(this, R.anim.left_out_slow);
//		right_in = AnimationUtils.loadAnimation(this, R.anim.right_in_slow);
//		right_out = AnimationUtils.loadAnimation(this, R.anim.right_out_slow);
//	}

	LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
			LayoutParams.FILL_PARENT);

	@Override
	public void setupView() {
		// TODO Auto-generated method stub
		detailVeiw.setVisibility(View.VISIBLE);
		 sortAdapter = new SortAdapter(sorts, R.layout.mobile_album_sort_item, R.id.mobile_album_sort_item_tv, hasMore, context);
		 sort.setAdapter(sortAdapter);


		urls = albums.get("全部");

		adapter = new ViewAdapter(urls);
//		pager.removeAllViews();
		pager.setVisibility(View.VISIBLE);
		pager.setAdapter(adapter);
		
		loading.setVisibility(View.VISIBLE);
		
		
		dataChanageView(currentIndex);

		

	}

	@Override
	public void addListener() {
		// TODO Auto-generated method stub
		
		
		sort.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				DebugTools.log(className, "position = "+ position +"   currentSort = " + currentSort);
//				if(currentSort == position){
//					return ;
//				}
				Brand brand = (Brand) sortAdapter.getItem(position);
				sortAdapter.tvs.get(currentSort).setBackgroundResource(R.drawable.bg_transparent);
				currentSort = position ;
				sortAdapter.tvs.get(currentSort).setBackgroundResource(R.drawable.sort_text_select_bg);
				urls = albums.get(brand.brand_name);
//				dataChanageList(urls) ;
				currentIndex = 0 ;
				adapter = new ViewAdapter(urls);
//				pager.removeAllViews();
				pager.setAdapter(adapter);
				dataChanageView(currentIndex);
			}
		});
		
		pager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
				currentIndex = position;
//				dataChanageIndex();
				setCurrentIndex(); 
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub

			}
		});
		
//		ViewPagerClickListener listener = new ViewPagerClickListener();
//		pager.setClickable(true);
//		pager.setLongClickable(true);
//		pager.setOnClickListener(listener);
//		pager.setOnLongClickListener(listener);
		

	}

	@Override
	public void getData(){
		try {
			// TODO Auto-generated method stub
//			Intent intent = getIntent();
			String id = getIntent().getStringExtra("id");
//			image_nickname = intent.getStringExtra("image_nickname");
			if (id == null || "".equals(id)) {
				// Toast.makeText(this, "获取数据失败。。。", Toast.LENGTH_SHORT).show();
				return;
			}

			String urlPath = HttpUtils.BASE_URI + "prodimg?id=" + id;

			String jsonString = HttpUtils.getJsonString(urlPath);
			DebugTools.log(className, "jsonString :" + jsonString);

			List<Map<String, Object>> list = GSonTools.getMulObjectList(jsonString);

			albums = new HashMap<String, List<String>>();
			sorts = new ArrayList<Brand>();
			List<String> all = new ArrayList<String>();
			albums.put("全部", all);
			Brand b = new Brand() ;
			b.brand_name = "全部" ;
			b.brand_id = "0";
			sorts.add(b);
			for (Map<String, Object> map2 : list) {
				List<String> nowList = null;
				String sort_name = (String) map2.get("sort_name");
				if (albums.containsKey(sort_name)) {
					nowList = albums.get(sort_name);
				} else {
					nowList = new ArrayList<String>();
					albums.put(sort_name, nowList);
					Brand brand = new Brand() ;
					brand.brand_name =sort_name ;
					brand.brand_id = sorts.size()+"" ;
					sorts.add(brand);
				}

				List<Map<String, String>> photos = (List<Map<String, String>>) map2
						.get("photos");
				for (Map<String, String> map3 : photos) {
					String album = map3.get("image_name");
					if (image_id != null && !image_id.equals("")
							&& image_id.equals(map3.get("image_id"))) {
						currentIndex = all.size();
					}
					nowList.add(album);
					all.add(album);
				}

			}

			DebugTools.log(className, "sorts = " + sorts + "  " + sorts.size());
			allCounts = all.size() - 1;
			currentSort = 0;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e) ;
		}

	}

	private void dataChanageList(List<String> albumsUrl) {
		adapter.dataChanage(albumsUrl);
		currentIndex = 0;
		allCounts = albumsUrl.size() - 1;
		setCurrentIndex();
		setAllCount();
	}

	private void dataChanageView(int currentIndex) {
		this.currentIndex = currentIndex;
		allCounts = urls.size() - 1;
		setCurrentIndex();
		setAllCount();
		pager.setCurrentItem(currentIndex);
	}



	private void setPageText(TextView tv, int i) {
		tv.setText(i + 1 + "");
	}

	private void setCurrentIndex() {
		if(currentIndex==0){
			Toast.makeText(context, "第一张", Toast.LENGTH_SHORT).show();
		}else if(currentIndex == adapter.getCount()-1){
			Toast.makeText(context, "最后一张", Toast.LENGTH_SHORT).show();
		}
		setPageText(currentIndexTV, currentIndex);
	}

	private void setAllCount() {
		setPageText(allCountsTV, allCounts);
	}

	@Override
	public void doClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {

		default:
			break;
		}

	}

	class ViewAdapter extends PagerAdapter implements OnClickListener, OnLongClickListener{
		private ArrayList<ImageView> views;
		List<String> albumsUrl;
		private  int len ;
		public void dataChanage(List<String> albumsUrl){
			this.albumsUrl = albumsUrl ;
			initView() ;
		}
		public ViewAdapter(List<String> albumsUrl) {
			super();
			this.albumsUrl = albumsUrl;
			views = new ArrayList<ImageView>();
			initView() ;
		}
		
		private void initView(){
			len = albumsUrl.size() ;
			LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,
					LayoutParams.WRAP_CONTENT);
			views.clear() ;
			for (int i = 0; i < len; i++) {
				ImageView iv = new ImageView(context);
				iv.setClickable(true);
				iv.setLongClickable(true);
				iv.setOnClickListener(this);
				iv.setOnLongClickListener(this);
				iv.setLayoutParams(params);
				iv.setPadding(2, 0, 2, 0);
				iv.setScaleType(ScaleType.FIT_CENTER);
				views.add(iv);
			}
			
		}
		
		

		@Override
		public void destroyItem(View pager, int position, Object arg2) {
			// TODO Auto-generated method stub
//			if(position%3==0){
//				BitmapUtils.cleanCache();
//			}
			View view = views.get(position);
			((ViewPager) pager).removeView(view);
			ImageView iv = (ImageView) view ;
			Bitmap bm = iv.getDrawingCache(true) ;
			iv.setImageResource(R.drawable.bg_transparent);
			if(bm!=null&&!bm.isRecycled()){
				bm.recycle();
				bm = null ;
				iv = null ;
				System.gc();
			}
		}

		@Override
		public void finishUpdate(View arg0) {
			// TODO Auto-generated method stub

		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return len;
		}

		@Override
		public Object instantiateItem(View pager, int position) {
			// TODO Auto-generated method stub
			ImageView view = views.get(position);
//			BitmapUtils.loaderImage(albumsUrl.get(position), view, context);
			albumLoadPool.LoadImage(view, albumsUrl.get(position));
			((ViewPager) pager).addView(view);
			return view;
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			// TODO Auto-generated method stub
			return arg0 == arg1;
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
			// TODO Auto-generated method stub

		}

		@Override
		public Parcelable saveState() {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
			// TODO Auto-generated method stub

		}
		
		
		private String getItem(int position){
			if(null==albumsUrl||albumsUrl.isEmpty()||albumsUrl.size()<position+1){
				return "" ;
			}else{
				return albumsUrl.get(position);
			}
		}
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
//			String url = adapter.getItem(currentIndex);
//			log(currentIndex+"、单击  URL："+url) ;
			imageZoom(getItem(currentIndex));
		}

		@Override
		public boolean onLongClick(View v) {
			// TODO Auto-generated method stub
//			String url = adapter.getItem(currentIndex);
//			log(currentIndex+"、长按  URL："+url) ;
			imageZoom(getItem(currentIndex));
			return false;
		}

	}
	
	
	
	
	public static void log(String info){
		Log.i("MobileAlbumDetail", info);
	}
	
	
	

}